package cn.piggy.executor;


import cn.piggy.listener.PiggyEventSourceListener;
import cn.piggy.type.AiType;
import cn.piggy.util.OkHttpClientUtil;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class SimpleExecutor implements IExecutor {

    private final AiType aiType;

    public SimpleExecutor(AiType aiType) {
        this.aiType = aiType;
    }

    @Override
    public String sync(Object object) throws IOException {
        Request request = aiType.getRequestObject(object);
        Response response = OkHttpClientUtil.getOkHttpClient().newCall(request).execute();
        ResponseBody body = response.body();
        if(body!=null){
            return body.string();
        }
        return null;
    }

    @Override
    public void async(Object object, EventSourceListener eventSourceListener) throws IOException {
        Request request = aiType.getRequestObject(object);
        EventSource.Factory factory = EventSources.createFactory(OkHttpClientUtil.getOkHttpClient());
        factory.newEventSource(request, eventSourceListener);
    }

}
